package com.bishe.utils;

import com.bishe.dao.UserDao;
import com.bishe.pojo.Admin;
import com.bishe.pojo.User;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @date 2022/2/24 15:57
 */
public class JobUtil {


    /**
     * 检查用户登录
     */
    public static void checkUserLogin(HttpServletRequest request,JdbcTemplate jdbcTemplate) {
        String token = request.getHeader("token");

        if (token == null){
            throw new EcoBootException("未登录！");
        }

            //token无效  代表未登录
            if (JwtUtil.verify(token)) {
                //查找用户是否存在
                User byId = new SqlQueryUtils<User>(User.class, jdbcTemplate).eq(User::getId, JwtUtil.getUserId(token)).getOne();

                //代表 已登录
                if (byId != null)return;

               throw new NotLoginException("未登录！");
            }
    }


    /**
     * 检查管理员登录
     */
    public static void checkAdminLogin(HttpServletRequest request,JdbcTemplate jdbcTemplate) {
        String token = request.getHeader("token");

        if (token == null){
            throw new EcoBootException("未登录！");
        }

        //token无效  代表未登录
        if (JwtUtil.verify(token)) {

            //查找用户是否存在
            Admin byId = new SqlQueryUtils<Admin>(Admin.class, jdbcTemplate).eq(Admin::getId, JwtUtil.getUserId(token)).getOne();
            //代表 已登录
            if (byId != null)return;

            throw new NotLoginException("未登录！");
        }
    }

    /**
     * 获取用户id
     */
    public static String getUserId(HttpServletRequest request) {
        String token = request.getHeader("token");

        return JwtUtil.getUserId(token);
    }

    /**
     * 获取用户类型
     * @param request
     * @return
     */
    public static String getUserType(HttpServletRequest request){
        String token = request.getHeader("token");

        return JwtUtil.getUsername(token);
    }

    /**
     * 登录
     *
     * @param type   角色
     * @param userId 用户id
     */
    public static String login(String type, String userId) {
         return JwtUtil.sign(type, userId);
    }




    public static void main(String[] args) {


    }

}
